package com.easypan.controller;

import cn.dsna.util.images.ValidateCode;
import com.easypan.Service.EmailCodeService;
import com.easypan.Service.UserService;
import com.easypan.annotation.GlobalInterceptor;

import com.easypan.entity.configA.cofig;
import com.easypan.entity.constants.Constants;
import com.easypan.entity.dto.SessionwebUserDto;
import com.easypan.entity.dto.UserSpaceDto;
import com.easypan.entity.po.UserInfo;
import com.easypan.entity.vo.R;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;

@RestController
public class userController {
@Resource
private EmailCodeService emailCodeService;
@Autowired
private UserService userService;
@Autowired
    private cofig  cofig;
    @GetMapping("/checkCode")
    public void checkCode(HttpServletRequest req, HttpServletResponse resp,Integer type) throws IOException {
        ValidateCode validateCode = new ValidateCode(200,30,4,20);
        String codes = validateCode.getCode();
        HttpSession session = req.getSession();

        //0:登录注册 1:邮箱验证码发送 默认0
        if(type==1)
        {
            session.setAttribute(Constants.CHECK_CODE_KEY_EMAIL,codes);
        }else
        {
            session.setAttribute(Constants.CHECK_CODE_KEY,codes);
        }
        ///同一个请求 的seiion 我们有可能存储着两个验证码
        validateCode.write(resp.getOutputStream());

    }
    @PostMapping ("/sendEmailCode")
    public R sendEmailCode(String email, String checkCode, String type, HttpSession session,HttpServletRequest request)
    {

        //1.判断验证码是否正确
        String code = (String) session.getAttribute(Constants.CHECK_CODE_KEY_EMAIL);

        //2.错误返回
        if(code == null || !code.equalsIgnoreCase(checkCode))
        {
            session.removeAttribute(Constants.CHECK_CODE_KEY_EMAIL);
            return R.error("验证码错误");
        }
        //3.正确
        session.removeAttribute(Constants.CHECK_CODE_KEY_EMAIL);
        R r = emailCodeService.sendEmail(email, type,request);

        return r;
    }
//注册逻辑--无论是成功还是失败 都需要 清楚验证码 防止对方攻击
    @PostMapping ("/register")
    public  R register(String email, String nickName, String password, String emailCode,String checkCode,HttpServletRequest req)
    {
        HttpSession session=req.getSession();
        R zuce = userService.zuce(req, email, nickName, password, password, emailCode, checkCode);
        session.removeAttribute(Constants.CHECK_CODE_KEY);

        return zuce;
    }
//无论有没有都需要清楚数据
    @PostMapping("/login")
    public R zhuce(String email,String password,String checkCode,HttpServletRequest req)
    {
        R dl = userService.dl(email, password, checkCode, req);
        if(Objects.nonNull(dl.getData()))
        {
            SessionwebUserDto data = (SessionwebUserDto) dl.getData();
            HttpSession session=req.getSession();
            session.setAttribute("session_key",data);
        }
       HttpSession session=req.getSession();
        session.removeAttribute(Constants.CHECK_CODE_KEY);
        return dl;
    }

    @PostMapping("/resetPwd")
    public  R zhmm(String email,String password,String checkCode,String emailCode,HttpServletRequest req)

    {
        R xgmm = userService.xgmm(email, password, checkCode, emailCode, req);
       HttpSession session=req.getSession();
        session.removeAttribute(Constants.CHECK_CODE_KEY);
        return xgmm;
    }
///头像
    ///TOOD-- 外部接口 --可能会被刷爆
    @GetMapping("getAvatar/{userId}")
    ///@GlobalInterceptor
    public  R tx(@PathVariable("userId") int userId,HttpServletResponse response) throws IOException {
//1.存储本地 --用mysql对应ID--进行查找文件——-
        //路径

        String path=cofig.getBasePath();
        path=path + userId+"."+"jpg";
        File file = new File(path);
        if(!file.exists())
        {
            //没有头像 给默认路径
            path=cofig.getBasePath() + 1+"."+"jpg";
        }
        FileInputStream fileInputStream= null;
        try {
            fileInputStream = new FileInputStream(new File(path));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        ServletOutputStream outputStream=response.getOutputStream();
        response.setContentType("image/jpeg");
        int len=0;

        byte[] bytes=new byte[1024];

        //读取文件内容拼凑发送
        //读内容到缓冲器 另利用输入流进行发送
        while ( (len=fileInputStream.read(bytes) ) != -1     )
        {
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        //关闭资源
        outputStream.close();
        fileInputStream.close();

        return null;
    }
    ///上传头像
   @PostMapping("/updateUserAvatar")
   @GlobalInterceptor
    public R updateUserAvatar(HttpSession session, @RequestParam("avatar")MultipartFile multipartFile)
   {
    //1.拿出userid
       SessionwebUserDto sessionKey = (SessionwebUserDto) session.getAttribute("session_key");
      String id= String.valueOf(sessionKey.getUserId());
      if(id==null)
      {
          R.error("用户不匹配");
      }
       //2.清空qq 本地头像的优先级 高于QQ回传的优先级
       UserInfo userInfo=new UserInfo();
       userInfo.setQqAvatar("");
       userInfo.setUserId(String.valueOf(sessionKey.getUserId()));
       userService.qqtxqk(userInfo);

       //3.将文件流根据userid保存到硬盘
       //1.获取原文件名字
       String originalFilename=multipartFile.getOriginalFilename();
       //截取文件名后缀
       String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));

       String fileName=sessionKey.getUserId()+suffix;

       //2.文件保存路径  ->路径进行配置
       File dir=new File(cofig.getBasePath());
       if(!dir.exists())
       {
           dir.mkdirs();
       }
       //将文件进行转存
       try {
           multipartFile.transferTo(new File(cofig.getBasePath()+fileName));
       } catch (IOException e) {
           throw new RuntimeException(e);
       }
       return  R.success(fileName);
   }

   @PostMapping ("/logout")
    public  R logout(HttpSession session)
   {
       session.invalidate();
     return   R.success("退出登录成功");
   }

   @PostMapping("/qqlogin")
    public R qqlogin(String callbackUrl)
   {

       return null;
   }

   ///getUseSpace
    @PostMapping("/getUseSpace")
    public R getUseSpace(HttpSession session)
    {
        ///TOOD:将这种数据存入redis--包括-文件列表也可以存入
        R r=userService.getUserSpace(session);
        return r;
    }
}
